/**
 * Created by Administrator on 2017/7/26.
 */

$(document).ready(function () {

//商品信息
    var shoptpl=$('#discount-list-template').html();
    var shopTemplate=Handlebars.compile(shoptpl);
//商品类别
    var selectTpl=$('#select-template').html();
    var selectCmp=Handlebars.compile(selectTpl);

//首页数据
    var uri=C.interface.discount;
//获取商品分类
    var selectUri=C.interface.selectType;

//ajax加载商品列表
    var categoryId='',orderType='',pageLength=10,minMaxPrice='',minMaxSales='';

    var range = 200, //距下边界长度/单位px
        maxnum = 0, //设置课程总数
        num = 0, //当前数量
        totalheight = 0,
        flag=0,
        start=0,
        searchName='';
    var servenBack = null,
        percentFeedback = null;

//获取商品类别(全部，男装，女装)
    $.ajax({
        url:selectUri,
        type:'POST',
        dataType:'json',
        data:{},
        success:function (response) {
            if (response.result=='success'){
                var selectData=response.data;
                $('#dis-select-box').html(selectCmp(selectData));

                ajaxGetShopData();
                $(document).on('change','.dis-shop-type',function () {
                    $('#dis-list-vessel').empty();
                    categoryId=$(this).val();
                    console.log(categoryId);
                    num=0;
                    start = num;
                    ajaxGetShopData();
                });
                $(document).on('change','.dis-shop-sort',function () {
                    $('#dis-list-vessel').empty();
                    orderType=$(this).val();
                    console.log(orderType);
                    num=0;
                    start = num;
                    ajaxGetShopData();
                });

                /*筛选按钮的切换*/
                $('.dis-screen-btn').click(function () {
                    $(this).toggleClass('dis-screen-active');
                    $('.dis-screen').toggle();
                });

                //点击确定筛选
                $('#nmbConfirm').bind('click',getScreen);


            }else if (response.result=='login'){
                alert('您还没有登录，请登录');
                againLogin();
            }else {
                alert(response.errorMsg);
            }
        }

    });

//监听滚动高度，加载数据
    $(window).on('scroll',function () {
        var srollPos = $(window).scrollTop(); //滚动条距顶部距离(页面超出窗口的高度)
        //console.log("滚动条到顶部的垂直高度: " + $(document).scrollTop());
        //console.log("页面的文档高度 ："+$(document).height());
        //console.log('浏览器的高度：'+$(window).height());
        totalheight = parseFloat($(window).height()) + parseFloat(srollPos);


        if (num>=maxnum){
            return;
        }
        if (($(document).height()-range)<=totalheight&&num<maxnum){
            //这里不能使用模板填充，应该是append()....
            ajaxGetShopData();
        }
    });


    //搜索功能
    //手机端软键盘搜索
    $('.search-form').submit(function (e) {
        e.preventDefault();
        searchName= $('#search-input').val();
        if (searchName==''){
            return false;
        }
        $('#dis-select-box').hide();
//        清空
        $('#dis-list-vessel').empty();
        num =start = 0;
        ajaxGetShopData();
    });

    //点击搜索框开始搜索内容,请求后台接口
    $('.aui-searchbar-btn').click(function (e) {
        $('.search-from').trigger('submit');
        searchName= $('#search-input').val();
        if (searchName==''){
            return false;
        }
        $('#dis-select-box').hide();
//        清空
        $('#dis-list-vessel').empty();
        num =start = 0;
        ajaxGetShopData();

    });


    //$(document).on('change','.dis-shop-type',getShopSelected);
    //$(document).on('change','.dis-shop-sort',getShopSort);



    $('.all-mask').bind('click',function () {
        $('.dis-screen-price').hide();
    });




    //商品筛选
    function getScreen() {
        // $('.all-mask').show();
        //        全部
        var shopType=$('.dis-shop-type').val();
        //        默认排序
        var shopSales=$('.dis-shop-sort').val();
        //          最低价
        var lowPrice=$('.dis-low-price').val();
        //          最高价
        var highPrice=$('.dis-high-price').val();
        //         最低销量
        var lowSales=$('.dis-low-sales').val();
        //        最高销量
        var highSales=$('.dis-high-sales').val();
        //        最低价-最高价
        minMaxPrice=lowPrice+'-'+highPrice;
        //        最低销量-最高销量
        minMaxSales=lowSales+'-'+highSales;
        //        定义一个变量

        //      退货免运费选项是否选中
        if ($('.servenBack').is(':checked')){
            servenBack=1;
        }else {
            servenBack=null;
        }

        //      好评率
        if ($('.percentFeedback').is(':checked')){
            percentFeedback=1;
        }else {
            percentFeedback=null;
        }

        //        如果 最低价-最高价  最低销量-最高销量  =空
        if (lowPrice==''&&highPrice==''&&lowSales==''&&highSales=='' && percentFeedback==null &&servenBack==null){
            alert('没有填写筛选数据');
            // $('.all-mask').hide();
            // $('.dis-screen-btn').removeClass('dis-screen-active');
            // $('.dis-screen').hide();
            return false;
        }
        //最低价不能大于最高价
        if (parseInt(lowPrice) >= parseInt(highPrice)){
            alert('最低价不能大于最高价');
            return false;
        }
        if (parseInt(lowSales) >= parseInt(highSales)) {
            alert('最低销量不能大于最高销量');
            return false;
        }

        $('.dis-screen').toggle();
        $('#dis-list-vessel').empty();

        //清空搜索数据
        $('.dis-low-price').val('');
        $('.dis-high-price').val('');
        $('.dis-low-sales').val('');
        $('.dis-high-sales').val('');
        num =start = 0;
        ajaxGetShopData();
    }
//获取全部商品信息
    function ajaxGetShopData() {
        if (flag){
            return;
        }
        $('.no-info').hide();
        $('.loading').show();

        flag=1;
        $.ajax({
            url:uri,
            type:'POST',
            dataType:'json',
            data:{
                categoryId:categoryId,
                orderType:orderType,
                start:start,
                length:pageLength,
                minMaxPrice:minMaxPrice,
                minMaxSales:minMaxSales,
                name:searchName,
                percentFeedback:percentFeedback,
                servenBack:servenBack
            },
            success:function (response) {
                if (response.result=='success'){

                    minMaxPrice='';
                    minMaxSales='';

                    $('.loading').hide();
                    num++;
                    var data=response.data;
                    maxnum=data['productCount'];
                    start=num*pageLength;
                    if(maxnum == 0){
                        $(".no-info").show();
                    }
                    if (data.products.length>0){
                        $('#dis-list-vessel').append(shopTemplate(data));
                        new auiLazyload({
                            errorImage:'../img/errorimg.png'
                        });
                        // lazyload();
                        // console.log('数据加载成功')


                    }else {
                        $(".no-info").show();
                        num=maxnum+1;
                    }
                    flag=0;

                }
            }
        });

    }


//
    Handlebars.registerHelper('hongbao',function (sales) {
        if (sales==null){
            return null;
        }else {
            return sales;
        }
    });
//包邮不包邮
    Handlebars.registerHelper('exemption',function (value) {
        if (value=='001'){
            return '退货免邮费';
        }else if (value=='002'){
            return '退货不包邮';
        }
    });


    $(document).ready(function () {
        new auiLazyload({
            errorImage:'../img/errorimg.png'
        });
    });

//点击搜索,检索内容
    function searchCommodity() {
        var inputVal= $('#search-input').val();
        if (inputVal==null||inputVal==''){
            return false;
        }
        $('#dis-select-box').hide();
//        清空
        $('#dis-list-vessel').empty();
        num = 0;
        start = num;
        ajaxGetShopData();
    }

//删除文本之后请求数据。
    $(document).on('click', '#clean-search', function () {
        $('#dis-select-box').show();
        $('#dis-list-vessel').empty();
        searchName = '';
        num = 0;
        start = num;
        ajaxGetShopData();
    });
});